package cn.icanci.loopstack.amc.cloud.common.utils;

import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import cn.icanci.loopstack.amc.cloud.common.request.MockCallRequest;
import cn.icanci.loopstack.amc.cloud.common.response.MockCallResponse;
import cn.icanci.loopstack.api.client.Client;
import cn.icanci.loopstack.api.client.http.HttpClientImpl;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;

/**
 * Mock Call Utils
 * 
 * @author icanci
 * @since 1.0 Created in 2023/01/23 20:36
 */
public class MockCallUtils {
    private static final Logger logger      = LoggerFactory.getLogger(MockCallUtils.class);

    private static final Client HTTP_CLIENT = HttpClientImpl.getInstance();

    private MockCallUtils() {
    }

    /**
     * 执行Mock请求
     *
     * @see WrapperUtils 结果使用WrapperUtils进行返回处理
     * 
     * @param request mock请求
     * @param amcUrl 请求的 AMC Cloud 服务地址
     * @return 返回MockCallResponse
     */
    public static MockCallResponse doMockCall(MockCallRequest request, String amcUrl) {
        Client.RpcRequest rpcRequest = new Client.RpcRequest(amcUrl, request, Maps.newHashMap(), Method.POST, 3, TimeUnit.SECONDS, 0);
        logger.info("[MockCallUtils][doMockCall] req:{}", JSONUtil.toJsonStr(request));
        MockCallResponse call = HTTP_CLIENT.call(rpcRequest, MockCallResponse.class);
        logger.info("[MockCallUtils][doMockCall] resp:{}", JSONUtil.toJsonStr(call.getWrapper()));
        return call;
    }

    /**
     * 执行Mock请求，自定义执行参数
     *
     * @see WrapperUtils 结果使用WrapperUtils进行返回处理
     * 
     * @param request mock请求
     * @param amcUrl 请求的 AMC Cloud 服务地址
     * @param headers 请求的headers
     * @param method 请求的方法
     * @param readTimeout 请求超时时间
     * @return 返回MockCallResponse
     */
    public static MockCallResponse doMockCall(MockCallRequest request, String amcUrl, Map<String, String> headers, Method method, int readTimeout) {
        Client.RpcRequest rpcRequest = new Client.RpcRequest(amcUrl, request, headers, method, readTimeout, TimeUnit.SECONDS, 0);
        logger.info("[MockCallUtils][doMockCall] req:{}", JSONUtil.toJsonStr(request));
        MockCallResponse call = HTTP_CLIENT.call(rpcRequest, MockCallResponse.class);
        logger.info("[MockCallUtils][doMockCall] resp:{}", JSONUtil.toJsonStr(call.getWrapper()));
        return call;
    }
}
